package cn.frank.framework.caesar.module.ai.qwen.basic;

import dev.langchain4j.data.message.*;
import dev.langchain4j.model.chat.listener.ChatModelErrorContext;
import dev.langchain4j.model.chat.listener.ChatModelListener;
import dev.langchain4j.model.chat.listener.ChatModelRequestContext;
import dev.langchain4j.model.chat.listener.ChatModelResponseContext;
import dev.langchain4j.model.chat.request.ChatRequest;
import dev.langchain4j.model.chat.response.ChatResponse;

/**
 * @description: TODO
 * @author: renjiangyang
 * @date 2025/6/10 14:15:32
 * @since 1.8
 */
public class LoggingListener implements ChatModelListener {

    @Override
    public void onRequest(ChatModelRequestContext context) {
        ChatRequest chatRequest = context.chatRequest();
        System.out.println("➡️ 请求消息:");
        for (ChatMessage message : chatRequest.messages()) {
            if (message instanceof UserMessage user) {
                System.out.println("[USER] " + user.contents().toString());
            } else if (message instanceof AiMessage ai) {
                System.out.println("[AI] " + ai.text());
            } else if (message instanceof SystemMessage system) {
                System.out.println("[SYSTEM] " + system.text());
            } else if (message instanceof ToolExecutionResultMessage toolResult) {

            } else {
                System.out.println("[UNKNOWN] " + message.getClass().getSimpleName());
            }
        }

        // 可以记录时间戳用于耗时分析
        context.attributes().put("startTime", System.currentTimeMillis());
    }

    @Override
    public void onResponse(ChatModelResponseContext context) {
        long start = (long) context.attributes().getOrDefault("startTime", -1L);
        if (start != -1) {
            System.out.println("⏱️ 耗时：" + (System.currentTimeMillis() - start) + "ms");
        }

        ChatResponse response = context.chatResponse();
        System.out.println("✅ 响应消息: " + response.aiMessage().text());
    }

    @Override
    public void onError(ChatModelErrorContext context) {
        Throwable error = context.error();
        ChatRequest chatRequest = context.chatRequest();

        System.err.println("❌ 模型调用异常：" + error.getClass().getSimpleName() + ": " + error.getMessage());
        System.err.println("➡️ 异常时的请求消息：");
        for (ChatMessage message : chatRequest.messages()) {
            System.err.printf("  [%s] %s%n", message.type(), message);
        }

        long start = (long) context.attributes().getOrDefault("startTime", -1L);
        if (start > 0) {
            System.err.println("⏱️ 异常耗时：" + (System.currentTimeMillis() - start) + "ms");
        }
    }
}

